<?php

namespace app\api\controller;

use ba\Tree;
use Throwable;
use think\facade\Db;
use think\facade\Config;
use app\common\controller\Frontend;
use app\common\library\token\TokenExpirationException;
use app\ExceptionHandle;
use app\admin\model\Coupon as Model;


class Coupon extends Frontend
{
    protected array $noNeedLogin = [''];
    protected Model $model;

    public function initialize (): void
    {
        parent::initialize();
        $this->model = new Model();
    }

    /**
     * 用户的优惠券列表
     */
    public function userCoupon (): void
    {
        // halt($this->auth->id);
        $type = $this->request->param("type", 1);
        $where = [];

        $where[] = ['u.user_id', '=', $this->auth->id];
        if ($type == 1) {

            $where[] = Db::raw('u.is_apply = 1 and (u.end_time > "' . date("Y-m-d H:i:s", time()) . '" or u.end_time is null)');
        } else {
            $where[] = Db::raw('u.is_apply = 2 or u.end_time < "' . date("Y-m-d H:i:s", time()) . '"');
        }
        $list = Db::table("ba_user_coupon")
            ->alias('u')
            ->leftJoin('coupon c', 'ba_user_coupon.coupon_id = c.coupon_id')
            ->where($where)
            ->field("ba_user_coupon.*,c.coupon_id,c.price,c.name,c.title")
            ->paginate(10)
            ->each(function ($item) {
                $text = "待使用";

                if (!empty($item['end_time'])) {
                    $endtime = strtotime($item["end_time"]);
                    if ($item['is_apply'] == 2) $text = "已使用";
                    if ($endtime < time()) {
                        $text = "已过期";
                        $item['is_apply'] = 2;
                    }
                }
                $item['text'] = $text;

                return $item;
            });


        $this->success("", [
            'list'  => $list->items(),
            'total' => $list->total(),
        ]);
    }

}